package com.github.hgkmail.hello.interceptor;

import com.github.hgkmail.hello.annotation.Walk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class WalkInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(WalkInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(Walk.class)) {
                Walk walk = method.getAnnotation(Walk.class);
                logger.info("Walk pre: {}", walk.word());
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(Walk.class)) {
                Walk walk = method.getAnnotation(Walk.class);
                logger.info("Walk post: {}", walk.word());
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(Walk.class)) {
                Walk walk = method.getAnnotation(Walk.class);
                logger.info("Walk complete: {}", walk.word());
            }
        }
    }

}
